package com.sikaryofficial.file.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件完整性校验工具类
 *
 * @author qinjinyuan
 */
@Slf4j
public class FileMD5Utils {
    public static String generateFileMd5(MultipartFile multipartFile) {
        try (InputStream inputStream = multipartFile.getInputStream()) {
            byte[] bytes = IoUtil.readBytes(inputStream);
            return DigestUtil.md5Hex(bytes);
        }catch (Exception e){
            log.error("文件完整性校验-MD5生成失败");
        }
        return null;
    }

    /**
     * 生成基于多个参数的 MD5 哈希值。
     *
     * @param file 文件对象
     * @param audioPath 音频路径
     * @param audioStartTime 音频开始时间
     * @param audioDuration 音频持续时间
     * @return MD5 哈希值字符串
     */
    public static String generateMD5Hash(MultipartFile file, String audioPath, String audioStartTime, String audioDuration, String videoCoverUrl) {
        try {
            // 将所有参数按顺序拼接成一个字符串
            String input = new String(file.getBytes()) + audioPath + audioStartTime + audioDuration + (CharSequenceUtil.isBlank(videoCoverUrl)? "" : videoCoverUrl) ;
            // 创建 MessageDigest 实例
            MessageDigest digest = MessageDigest.getInstance("MD5");
            // 计算 MD5 哈希值
            byte[] hash = digest.digest(input.getBytes());
            // 转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5哈希值生成失败", e);
            throw new RuntimeException("Failed to generate MD5 hash", e);
        } catch (Exception e) {
            log.error("文件读取失败", e);
            throw new RuntimeException("Failed to read file content", e);
        }
    }
}